//
//  CHLocationManager.swift
//  bridging_js
//
//  Created by cyptt on 2021/9/7.
//
/**
 SWIFT 版本 还有一个oc版本
 */
import UIKit
import CoreLocation

typealias ClosureSuccess = (Dictionary<String, Any>) -> ()
typealias ClosureFail = (String) -> ()

public class CHLocationManager: NSObject,CLLocationManagerDelegate {

    
    public static let shared = CHLocationManager()
    
    var clousreSuccess : ClosureSuccess?
    var clousreFail : ClosureFail?
    private var locationManager : CLLocationManager?
    private var viewController : UIViewController?      // 承接外部传过来的视图控制器，做弹框处理
    
    
   public func getLocationInfo(locationInfo:@escaping ((_ info:Dictionary<String, Any>)->Void),fail:@escaping (_ err:String)->Void){
        self.clousreSuccess = locationInfo
        self.clousreFail = fail
    }
    // 外部初始化的对象调用，执行定位处理。
  public  func startPositioning(_ vc:UIViewController) {
        viewController = vc
        if (self.locationManager != nil) && (CLLocationManager.authorizationStatus() == .denied) {
            // 定位提示
            alter(viewController: viewController!)
        } else {
            requestLocationServicesAuthorization()
        }
    }
    
    
    // 初始化定位
    private func requestLocationServicesAuthorization() {
        
        if (self.locationManager == nil) {
            self.locationManager = CLLocationManager()
            self.locationManager?.delegate = self
        }
        
        self.locationManager?.requestWhenInUseAuthorization()
        self.locationManager?.startUpdatingLocation()
        
        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined) {
            locationManager?.requestWhenInUseAuthorization()
        }
        
        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse) {
            locationManager?.desiredAccuracy = kCLLocationAccuracyBest
            let distance : CLLocationDistance = 10.0
            locationManager?.distanceFilter = distance
            locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager?.startUpdatingLocation()
        }
    }
    
    
    // 获取定位代理返回状态进行处理
    private func reportLocationServicesAuthorizationStatus(status:CLAuthorizationStatus) {
        
        if status == .notDetermined {
            // 未决定,继续请求授权
            requestLocationServicesAuthorization()
        } else if (status == .restricted) {
            // 受限制，尝试提示然后进入设置页面进行处理
            alter(viewController: viewController!)
        } else if (status == .denied) {
            // 受限制，尝试提示然后进入设置页面进行处理
            alter(viewController: viewController!)
        }
    }
    
    
    private func alter(viewController:UIViewController) {
        
    }
}
 
extension CHLocationManager {
    
    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        self.locationManager?.stopUpdatingLocation()
        
        let location = locations.last ?? CLLocation()
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
            
            if error != nil {
                if self.clousreFail != nil {
                    self.clousreFail!(error?.localizedDescription ?? "")
                }
                return
            }
            
            if let place = placemarks?[0]{
                
                print("---place",place)
                
                // 国家 省  市  区  街道  名称  国家编码  邮编
//                let country = place.country ?? ""
                let administrativeArea = place.administrativeArea ?? ""
                let locality = place.locality ?? ""
                let subLocality = place.subLocality ?? ""
                let thoroughfare = place.thoroughfare ?? ""
                let name = place.name ?? ""
                
//                let isoCountryCode = place.isoCountryCode ?? ""
//                let postalCode = place.postalCode ?? ""
                
                let longitude = location.coordinate.longitude  //经度
                let latitude = location.coordinate.latitude
            
                var resultMap:[String:Any] = [:]
                resultMap["administrativeArea"] = administrativeArea;
                resultMap["locality"] = locality
                resultMap["subLocality"] = subLocality
                resultMap["thoroughfare"] = thoroughfare
                resultMap["name"] = name
                resultMap["longitude"] = longitude
                resultMap["latitude"] = latitude
            
                if self.clousreSuccess != nil {
                    self.clousreSuccess!(resultMap)
                }
           
            } else {
                
                if self.clousreFail != nil {
                    self.clousreFail!("No placemarks!")
                }
            }
        }
    }
    
    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        reportLocationServicesAuthorizationStatus(status: status)
    }
    
    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        self.locationManager?.stopUpdatingLocation()
    }


}
